package teaching.interceptors;

import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import teaching.exception.NotAllowException;
import teaching.util.AuthAccess;
import teaching.util.JwtUtil;
import teaching.util.StatusCode;
import teaching.util.ThreadLocalUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * Author:20201002983_郑雨蓓
 * Date: 2024/3/2
 * Description:拦截器重写
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //令牌验证
        String token = request.getHeader("Authorization");
        try {
//            if (StrUtil.isBlank(token)) {
//                token = request.getParameter("token");//url参数 ?token=xxx
//            }
            //注解放行检测
            if (handler instanceof HandlerMethod) {
                AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
                if (annotation != null) {
                    return true;
                }
            }
            //两种方式接收完，开始认证
            if (StrUtil.isBlank(token)) {
                throw new NotAllowException(StatusCode.NO_TOKEN.code, "缺少权限，请登录");
            }
            Map<String, Object> claims = JwtUtil.parseToken(token);//拿到username
            //应该是传了
            ThreadLocalUtil.set(claims);
            //解析token不报错则放行
            return true;
        } catch (Exception e) {
            //验证令牌失败
            //http状态码为401
            throw new NotAllowException(StatusCode.NO_TOKEN.code, "缺少权限或权限过期");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
